<?php
class Core_Common_Paginator {
	private $_adapter;
	private $_select;
	private $_rowlimiter;
	private $_nbelement;
	private $_position;
	private $_nbpages;
	
	public function __construct(Core_Data_Mappers_Abstract $Adapter=null,$filter ,$rowlimiter = 5,$position=0) {
		if(!($Adapter instanceof Core_Data_Mappers_Abstract)) 
			throw new Exception("No adapter available");
			
		$this->_adapter = $Adapter;
		$this->_rowlimiter = $rowlimiter;
		$this->_position=$position;
		$this->_select = $filter;
		$countselect = $this->_adapter->getDbTable()->getAdapter()->select()->from($this->_adapter->getDbTable()->info('name'),array('rowcount'=>'count(*)'));
		if(isset($this->_select)) {
			foreach ($this->_select as $key=>$value)
				$countselect->where($key,$value);
		}
		$countselect->assemble();
		//var_dump($countselect->assemble());
		$row = $Adapter->getDbTable()->getAdapter()->fetchAll($countselect);
		//$row = $countselect->query();
		if(isset($row)&& count($row)==1) {
			$row=current($row);
			$this->_nbelement = intval($row['rowcount']);
			$this->_nbpages = ceil($this->_nbelement/$this->_rowlimiter);
		}
		
	}
	
	public function getPages($page=null) {
		$position = isset($page) && $page<=$this->_nbpages? ($page-1) * $this->_rowlimiter : ($this->_position-1) * $this->_rowlimiter;
		$position = $this->_nbpages>0 && $position/$this->_nbpages >=1 ? ($this->_nbpages-1) * $this->_rowlimiter : $position; 
		$position = $position < 0 ? 0 : $position; 
		$select = $this->_adapter->getDbTable()->select();
		if(isset($this->_select)) {
			foreach ($this->_select as $key=>$value)
				$select->where($key,$value);
		}
		$select->limit($this->_rowlimiter,$position);
		$rows = $this->_adapter->fetchQuery($select);
		//var_dump($rows);die;
		if(isset($rows) && current($rows) instanceof Core_Business_Abstract) {
			$this->_position = $this->_position+1<=$this->_nbpages?$this->_position+1:$this->_nbpages;
			return $rows;
		}
		return array();
	}
	
	public function getNbPage() {return $this->_nbpages;}
	
	public function getPosition() {return $this->_position;}
	public function setPosition($value) {$this->_position=$value;}
	
}
?>